/*
 * CustomListView.fx
 *
 * Created on Jun 19, 2009, 6:56:20 PM
 */

package com.gpsbuddy.components;

import javafx.geometry.BoundingBox;
import javafx.geometry.Bounds;
import javafx.scene.CustomNode;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.shape.Rectangle;
import javafx.scene.input.MouseEvent;

/**
 * @author josh
 */

public class CustomListView extends CustomNode {
    public var data:Object[] on replace {println("data replaced {scrollValue}"); adjust();};
    public var width = 100.0;
    public var height = 100.0;
    public var itemHeight = 10.0;

    var visibleCount:Integer = bind ((height / itemHeight) as Integer) + 1;
    var visibleStart = 0.0;
    var currentStartItem = 0;
    var yoff = 0.0;

    public var scrollValue = 0.0 on replace { adjust(); }
    
    function adjust() {
        visibleStart = scrollValue;
        var startItem = (visibleStart / itemHeight) as Integer;
        if(visibleStart >= 0) {
            yoff = -(visibleStart mod itemHeight);
        }
        if(startItem != currentStartItem) {
            currentStartItem = startItem;
            regen(startItem, startItem + visibleCount);
        }
    }

    function regen(start:Integer, end:Integer):Void {
        nodes = null;
        var e = end;
        if (end>data.size()){
            e = data.size()-1;
        }
        println("end {e}");
        for(i in [start..e]) {
            var bds = BoundingBox{ width: width height: itemHeight };
            var nd = createItemNode(data[i],bds);
            nd.translateX = 0;
            nd.translateY = indexof i * 30;
            insert nd into nodes;
        }
    }


    public var createItemNode: function(obj:Object, bounds:Bounds):Node;
    var nodes:Node[];

    override public function create():Node {
        return Group {
            content: Group { content: bind nodes translateY: bind yoff }
            clip: Rectangle { width: bind width height: bind height }
        }
    }

    override var onMouseWheelMoved = function(e: MouseEvent ):Void {
            scrollValue = scrollValue-(-1)*e.wheelRotation*itemHeight;
    }

    var offsetX: Number;
    var offsetY: Number;

     override def onMousePressed = function (evt: MouseEvent): Void {
        offsetX = scrollValue - evt.sceneX;
        offsetY = scrollValue - evt.sceneY;
    }

    override def onMouseDragged = function (evt: MouseEvent): Void {
        scrollValue = evt.dragAnchorY + evt.dragY + offsetY;
    }

    override def onMouseReleased = function (evt: MouseEvent) : Void {
        println(scrollValue);
    }

    init {
        regen(0,visibleCount);
    }

}

